package utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils {
    private static String url = null;
    private static String username = null;
    private static String password = null;
    static {

        try {
            // alt+enter 自动纠错
            // 读取配置
            InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            // 加载流
            properties.load(resourceAsStream);
            Class.forName(properties.getProperty("db.driver"));
            url = properties.getProperty("db.url");
            username = properties.getProperty("db.user");
            password = properties.getProperty("db.password");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    // 获取连接
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    // 释放资源
    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
        // 释放资源
        try {
            connection.close();
            preparedStatement.close();
            resultSet.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}
